<template>
  <div class="add-article-container">
    <Navbar />
    
    <el-container class="content-container">
      <el-aside width="280px">
        <el-card class="sidebar-card">
          <h3>发布指南</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="标题要求">简明扼要，突出重点，不超过30字</el-descriptions-item>
            <el-descriptions-item label="内容要求">内容积极健康，字数不少于200字</el-descriptions-item>
            <el-descriptions-item label="分类要求">请选择合适的文章分类</el-descriptions-item>
            <el-descriptions-item label="图片要求">建议上传相关图片，尺寸16:9</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-aside>
      
      <el-container>
        <el-header class="content-header">
          <h1>发布文章</h1>
        </el-header>
        
        <el-main class="article-form">
          <el-card class="form-card">
            <el-form 
              ref="articleForm" 
              :model="article" 
              :rules="rules" 
              label-width="100px"
            >
              <el-form-item label="文章标题" prop="title">
                <el-input v-model="article.title" placeholder="请输入文章标题" />
              </el-form-item>
              
              <el-form-item label="文章分类" prop="category">
                <el-select v-model="article.category" placeholder="请选择文章分类">
                  <el-option label="国内新闻" value="国内新闻" />
                  <el-option label="国际新闻" value="国际新闻" />
                  <el-option label="科技新闻" value="科技新闻" />
                  <el-option label="娱乐新闻" value="娱乐新闻" />
                  <el-option label="体育新闻" value="体育新闻" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="文章标签" prop="tags">
                <el-input
                  v-model="tagInput"
                  placeholder="输入标签，用逗号分隔"
                  @keyup.enter.native="addTag"
                >
                  <template #append>
                    <el-button @click="addTag" :disabled="!tagInput.trim()">添加</el-button>
                  </template>
                </el-input>
                <div class="tag-list">
                  <el-tag
                    v-for="(tag, index) in article.tags"
                    :key="index"
                    closable
                    @close="removeTag(index)"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </el-form-item>
              
              <el-form-item label="文章封面">
                <el-upload
                  class="upload-demo"
                  action="#"
                  list-type="picture"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                >
                  <el-button type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="upload-tip">建议尺寸：1200px × 675px，支持JPG、PNG格式</div>
                  </template>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="文章内容" prop="content">
                <el-input
                  v-model="article.content"
                  type="textarea"
                  :rows="20"
                  placeholder="请输入文章内容..."
                  style="width: 100%"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="submitArticle">发布文章</el-button>
                <el-button @click="cancel">取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import { useArticleStore } from '@/stores/articleStore'
import Navbar from '@/components/Navbar.vue'

const router = useRouter()
const userStore = useUserStore()
const articleStore = useArticleStore()
const articleForm = ref<HTMLFormElement | null>(null)

// 表单数据
const article = reactive({
  title: '',
  category: '',
  tags: [] as string[],
  content: '',
  image: '',
  author: userStore.user?.username || '',
  createdAt: new Date().toISOString()
})

// 标签输入
const tagInput = ref('')

// 上传文件列表
const fileList = ref([] as any[])

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  category: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
}

// 生命周期钩子
onMounted(() => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
  }
})

// 添加标签
const addTag = () => {
  const tag = tagInput.value.trim()
  if (tag && !article.tags.includes(tag)) {
    article.tags.push(tag)
    tagInput.value = ''
  }
}

// 移除标签
const removeTag = (index: number) => {
  article.tags.splice(index, 1)
}

// 处理文件上传预览
const handlePreview = (file: any) => {
  console.log('预览文件', file)
}

// 处理文件移除
const handleRemove = (file: any) => {
  console.log('移除文件', file)
  // 更新图片路径
  if (fileList.value.length === 0) {
    article.image = ''
  }
}

// 提交文章
const submitArticle = async () => {
  if (!articleForm.value) return
  
  await articleForm.value.validate(async (valid) => {
    if (valid) {
      // 处理图片上传（这里简化处理，实际项目中需要真实上传）
      if (fileList.value.length > 0) {
        article.image = fileList.value[0].url || ''
      }
      
      try {
        await articleStore.addArticle(article)
        ElMessage.success('文章发布成功')
        router.push('/')
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '文章发布失败，请重试')
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 取消发布
const cancel = () => {
  router.push('/')
}
</script>

<style scoped>
.add-article-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content-container {
  height: calc(100vh - 60px);
}

.content-header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 0 20px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.article-form {
  padding: 20px;
  background-color: #fff;
}

.form-card {
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 30px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.sidebar-card {
  height: 100%;
  border-radius: 0;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
}
</style>